#!/usr/bin/python
# -*- coding: utf-8 -*-

from scores import scores, AVG, MAX, MIN, STD, NUMBER, TEXT
from index import index
from rss import rss
from shutil import copy
from os import chmod, mkdir, access, F_OK, listdir
from os.path import expanduser
from stat import S_IRWXU, S_IRGRP, S_IXGRP, S_IROTH, S_IXOTH
from commands import getstatus, getoutput

PREPROCESSED_FILES = {}
AVERAGETYPES = []
NEWS = []

def M(id, scores):
    return -1.0

def log(s):
    print "%s" % (s)

def addFile(filename, script):
    PREPROCESSED_FILES[filename] = script

def addNews (day, month, topic, text):
    NEWS.append((month, day, topic, text))

def addAverageType(typename, caption, type):
    AVERAGETYPES.append((typename, caption, type))

URL = ""
EXTERNAL_FILES = []
TERM="none"
GROUPS_NAME = "none"
DISCIPLINE_NAME = "MC999"
DISCIPLINE_CODE = "Disciplina inválida"
TESTS = []
SCORED_TESTS = []
HIDDEN_TESTS = []
GROUPS=[]
BASEDIR=".."
GROUPDIR="alunos"
TESTSDIR="notas"
HTMLDIR="html"
AVERAGEFUNCTION=M
ABSENT_TEXT = "Ausente"
TEST_NOT_SCORED_TEXT = "Não corrigido"
LABELS = {}
CLASSES = {}
CLASSESDIR = "aulas"
CLASSPDF = "make -f $PWD/Makefile.aulas -C %(dir)s RADICAL=%(file)s " \
           "AULA=%(class)s HTMLDIR=%(htmldir)s pdf"
CLASSPDF4UP = "make -f $PWD/Makefile.aulas -C %(dir)s RADICAL=%(file)s " \
           "AULA=%(class)s HTMLDIR=%(htmldir)s pdf4up"
CLASSFILENAME="mc102-aula"
CLASSEXTRAS = ""
EXCLUDED_FILES = [".svn"]
SUSY_URL = ""

#Esse nao deve ser configurado pelo usuario
MODE = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH

STATS = []
STATSTEXT = "Estatísticas"
TABLE = False
TABLETEXT = "Tabela de notas"

if access("config.py", F_OK):
    execfile("config.py")

if access(expanduser("~/.emece.py"), F_OK):
    execfile(expanduser("~/.emece.py"))

# Copiando arquivos
log("Copiando arquivos externos")
for i in EXTERNAL_FILES + ["style.css"]:
    arq = i.split("/")[-1]
    copy(i, "%s/%s" % (HTMLDIR, arq))
    chmod("%s/%s" % (HTMLDIR, arq), MODE)

for i in PREPROCESSED_FILES.keys():
    log("Processando %s" % (i))
    getoutput(PREPROCESSED_FILES[i] %
              {"basedir": BASEDIR,
               "htmldir": HTMLDIR})
    chmod("%s/%s" % (HTMLDIR, i), MODE)

classconfig = "%s/%s/config.py" % (BASEDIR, CLASSESDIR) 
if access(classconfig, F_OK):
    execfile(classconfig)
else:
    log ("Arquivo de configuracao das aulas não"
         "encontrado em %s" % (classconfig))

# Compilando aulas
class_list = CLASSES.keys()
class_list.sort()
for i in class_list:
    if not access("%s/class%s" % (HTMLDIR, i), F_OK):
        mkdir("%s/class%s" % (HTMLDIR, i), MODE)
        chmod("%s/class%s" % (HTMLDIR, i), MODE)
    if CLASSPDF != "":
        log ("Compilando PDF da aula %s" % (i))
        getoutput(CLASSPDF % \
                        {"dir": "%s/%s/%s/" % (BASEDIR, CLASSESDIR, i),
                         "file": CLASSFILENAME,
                         "class": i,
                         "htmldir": "%s/class%s" % (HTMLDIR, i)})

    if CLASSPDF4UP != "":
        log ("Compilando PDF para impressão da aula %s" % (i))
        getoutput(CLASSPDF4UP % \
                        {"dir": "%s/%s/%s/" % (BASEDIR, CLASSESDIR, i),
                         "file": CLASSFILENAME,
                         "class": i,
                         "htmldir": "%s/class%s" % (HTMLDIR, i)})

    if CLASSEXTRAS != "":
        log ("Copiando extras da aula %s" % (i))
        files = [x for x in listdir("%s/%s/%s/%s/" % \
                                    (BASEDIR, CLASSESDIR, i, CLASSEXTRAS)) \
                 if x not in EXCLUDED_FILES]
        for x in files:
            arq = x.split("/")[-1]
            copy("%s/%s/%s/%s/%s" % (BASEDIR, CLASSESDIR, i, CLASSEXTRAS, x), \
                 "%s/class%s/%s" % (HTMLDIR, i, arq))
            chmod("%s/class%s/%s" % (HTMLDIR, i, arq), MODE)

    chmod("%s/class%s/%s%s.pdf" % (HTMLDIR, i,CLASSFILENAME,i), MODE)
    chmod("%s/class%s/%s%s-4up.pdf" % (HTMLDIR, i,CLASSFILENAME,i), MODE)
    
#Gerando a página inicial

log("Gerando página principal")
idx = index ()
idx.TERM = TERM
idx.GROUPS_NAME = GROUPS_NAME
idx.DISCIPLINE_NAME = DISCIPLINE_NAME
idx.DISCIPLINE_CODE = DISCIPLINE_CODE
idx.BASEDIR = BASEDIR
idx.HTMLDIR = HTMLDIR
idx.CLASSES = CLASSES
idx.CLASSPDF = CLASSPDF
idx.CLASSPDF4UP = CLASSPDF4UP
idx.CLASSEXTRAS = CLASSEXTRAS
idx.CLASSFILENAME = CLASSFILENAME
idx.LABELS = LABELS
idx.MODE = MODE
idx.SUSY_URL = SUSY_URL
idx.NEWS = NEWS
idx.generate_index_html()
idx.generate_windows_html()

log("Gerando RSS")
#Gerando notícias
fee = rss()
fee.TERM = TERM
fee.GROUPS_NAME = GROUPS_NAME
fee.DISCIPLINE_NAME = DISCIPLINE_NAME
fee.DISCIPLINE_CODE = DISCIPLINE_CODE
fee.BASEDIR = BASEDIR
fee.HTMLDIR = HTMLDIR
fee.NEWS = NEWS
fee.MODE = MODE
fee.URL = URL
fee.generate_rss()


#Copiando parâmetros necessários para a geração
#Das notas
log("Gerando notas")
sco = scores()
sco.TERM = TERM
sco.GROUPS_NAME = GROUPS_NAME
sco.DISCIPLINE_NAME = DISCIPLINE_NAME
sco.DISCIPLINE_CODE = DISCIPLINE_CODE
sco.TESTS = TESTS
sco.SCORED_TESTS = SCORED_TESTS
sco.HIDDEN_TESTS = HIDDEN_TESTS
sco.GROUPS = GROUPS
sco.BASEDIR = BASEDIR
sco.GROUPSDIR = GROUPSDIR
sco.TESTSDIR = TESTSDIR
sco.HTMLDIR = HTMLDIR
sco.AVERAGEFUNCTION = AVERAGEFUNCTION
sco.ABSENT_TEXT = ABSENT_TEXT
sco.TEST_NOT_SCORED_TEXT = TEST_NOT_SCORED_TEXT
sco.LABELS = LABELS
sco.MODE = MODE
sco.STATS = STATS
sco.STATSTEXT = STATSTEXT
sco.TABLE = TABLE
sco.TABLETEXT = TABLETEXT
sco.AVERAGETYPES = AVERAGETYPES
#Gerando as notas
sco.generate_scores()

